package com.qingcloud.common.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingcloud.base.constant.WamingConstant;
import com.qingcloud.common.auth.mapper.ClientMapper;
import com.qingcloud.common.auth.model.Client;
import com.qingcloud.common.auth.model.dto.ClientDTO;
import com.qingcloud.common.auth.service.OauthClientDetailService;
import com.qingcloud.base.constant.SecurityConstants;
import com.qingcloud.base.pojo.Result;
import com.qingcloud.base.service.impl.SuperServiceImpl;
import com.qingcloud.common.redis.template.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class OauthClientDetailServiceImpl extends SuperServiceImpl<ClientMapper, Client> implements OauthClientDetailService {
    @Resource
    private RedisUtil redisUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public Result<Client> saveClient(Client client) throws Exception {
        client.setClientSecret(passwordEncoder.encode(client.getClientSecretStr()));
        if(client.getId()!=null){
            client.setUpdateTime(LocalDateTime.now().format(WamingConstant.NORMAL_FULL_FORMATTER));
            super.updateById(client);
        }else{
            client.setUpdateTime(LocalDateTime.now().format(WamingConstant.NORMAL_FULL_FORMATTER));
            client.setCreateTime(LocalDateTime.now().format(WamingConstant.NORMAL_FULL_FORMATTER));
            super.save(client);
        }
        return Result.success(client);
    }
    @Override
    public Page<Client> listClient(ClientDTO dto, boolean isPage) {
        Page<Client> page;
        if (isPage) {
            page = new Page<>(dto.getPage(),dto.getLimit());
        } else {
            page = new Page<>(1, -1);
        }
        List<Client> list = baseMapper.findList(page, dto);
        page.setRecords(list);
        return page;
    }
    @Override
    public void delClient(long id) {
        Client client  = baseMapper.selectById(id);
        baseMapper.deleteById(id);

        String clientId = client.getClientId();
        redisUtil.del(clientRedisKey(clientId));
    }

    @Override
    public Client loadClientByClientId(String clientId) {
        QueryWrapper<Client> wrapper = Wrappers.query();
        wrapper.eq("client_id", clientId);
        return this.getOne(wrapper);
    }

    private String clientRedisKey(String clientId) {
        return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
    }
}
